package com.incar.chuxing.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.incar.chuxing.R;
import com.incar.chuxing.activity.PaymentActivity;
import com.incar.chuxing.activity.QualificationActivity;
import com.incar.chuxing.activity.MainActivity;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlConstant;
import com.incar.chuxing.bean.AlipayPreBean;
import com.incar.chuxing.bean.DepositCarResultEvent;
import com.incar.chuxing.bean.ResultBean;
import com.incar.chuxing.bean.WXPreBean;
import com.incar.chuxing.payment.AlipayUtils;
import com.incar.chuxing.payment.WXPayUtils;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.Dialogs.DepositDialog;
import com.incar.chuxing.utils.Dialogs.PayResultDialog;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.MyApplication;
import com.incar.chuxing.utils.SharedPreferencesKey;
import com.incar.chuxing.utils.SharedPreferencesUtils;
import com.incar.chuxing.utils.Toast.ToastCompat;
import com.umeng.analytics.MobclickAgent;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class DepositCarFragment extends Fragment {


    @BindView(R.id.carDeposit_ll)
    AutoLinearLayout carDepositLl;
    @BindView(R.id.carDeposit_weiXin)
    ImageView carDepositWeiXin;
    @BindView(R.id.car_deposit_wx)
    AutoRelativeLayout carDepositWx;
    @BindView(R.id.car_deposit_zfb)
    AutoRelativeLayout carDepositZfb;
    @BindView(R.id.car_deposit_line)
    View carDepositLine;
    @BindView(R.id.carDeposit_button_weiXin)
    RadioButton carDepositButtonWeiXin;
    @BindView(R.id.carDeposit_button_zfb)
    RadioButton carDepositButtonZfb;
    @BindView(R.id.pay_Cardeposit)
    TextView payCardeposit;
    @BindView(R.id.carDeposit_money)
    TextView carDepositMoney;
    @BindView(R.id.progress_bar)
    RelativeLayout progressBar;
    private Context mContext;
    private int payMethod = 0;
    private String identityStatus;
    private String licenseStatus;
    private String depositStatus;

    public DepositCarFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mContext = getContext();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_certify_deposit, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //显示可用的支付方式
        if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
            carDepositWx.setVisibility(View.VISIBLE);
            carDepositZfb.setVisibility(View.VISIBLE);
            carDepositLine.setVisibility(View.VISIBLE);
            carDepositButtonWeiXin.setChecked(true);
            carDepositButtonZfb.setChecked(false);
            payMethod = 1;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 0) {
            carDepositWx.setVisibility(View.VISIBLE);
            carDepositZfb.setVisibility(View.GONE);
            carDepositLine.setVisibility(View.GONE);
            carDepositButtonWeiXin.setChecked(true);
            carDepositButtonZfb.setChecked(false);
            payMethod = 1;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 0 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
            carDepositWx.setVisibility(View.GONE);
            carDepositZfb.setVisibility(View.VISIBLE);
            carDepositLine.setVisibility(View.GONE);
            carDepositButtonWeiXin.setChecked(false);
            carDepositButtonZfb.setChecked(true);
            payMethod = 2;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 0 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 0) {
            carDepositWx.setVisibility(View.GONE);
            carDepositZfb.setVisibility(View.GONE);
            carDepositLine.setVisibility(View.GONE);
            payMethod = 0;
        }


        carDepositButtonWeiXin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 1;
                    carDepositButtonZfb.setChecked(false);
                }
            }
        });

        carDepositButtonZfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 2;
                    carDepositButtonWeiXin.setChecked(false);
                }
            }
        });

        carDepositMoney.setText(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_CAR) / 100 + "");
    }

    @Subscribe
    public void onPayResult(DepositCarResultEvent event) {
        progressBar.setVisibility(View.GONE);
        identityStatus = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.REAL_NAME_STATUS);
        licenseStatus = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.LICENSE_CAR_STATUS);

        if (event.payResult == 0) {
            //1微信  2支付宝 3个人账户
            SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.DEPOSIT_CAR_STATUS, "1");//1交了保证金  0未交
            if (event.payMethod == 2 || event.payMethod == 1) {
                notifyPayDone();
            }
            final PayResultDialog payResultDialog = new PayResultDialog(mContext);
            payResultDialog.setResultTitle("支付成功");
            payResultDialog.setResultContent("您已缴纳保证金！");
            payResultDialog.setResultImage(R.drawable.icon_succeed);
            payResultDialog.show();
            new Handler(new Handler.Callback() {
                //处理接收到的消息的方法
                @Override
                public boolean handleMessage(Message arg0) {
                    //实现页面跳转
                    intentToNext();
                    if (payResultDialog != null) {
                        payResultDialog.dismiss();
                    }
                    return false;
                }
            }).sendEmptyMessageDelayed(0, 2000); //表示延时三秒进行任务的执行

        } else {
            final PayResultDialog payResultDialog = new PayResultDialog(mContext);
            payResultDialog.setResultTitle("支付失败");
            payResultDialog.setResultContent("付款失败，请选择重新付款！");
            payResultDialog.setResultImage(R.drawable.icon_fail);
            payResultDialog.show();
            new Handler(new Handler.Callback() {
                //处理接收到的消息的方法
                @Override
                public boolean handleMessage(Message arg0) {
                    //实现页面跳转
                    QualificationActivity activity = (QualificationActivity) getActivity();
                    activity.mVp.setCurrentItem(0);
                    activity.tvTitle.setText("缴保证金");
                    if (payResultDialog != null) {
                        payResultDialog.dismiss();
                    }
                    return false;
                }
            }).sendEmptyMessageDelayed(0, 1500); //表示延时三秒进行任务的执行

        }


    }

    private void intentToNext() {
        QualificationActivity activity = (QualificationActivity) getActivity();
        switch (identityStatus) {
            //身份证审核中
            //身份证审核成功
            case "11":
            case "13":
                switch (licenseStatus) {
                    //驾驶证未审核
                    //驾驶证失败
                    case "10":
                    case "12":
                        activity.mVp.setCurrentItem(2);
                        break;
                    //驾驶证审核中
                    //驾驶证审核成功
                    case "11":
                    case "13":
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_TRIP_METHOD, 1);
                        startActivity(new Intent(mContext, MainActivity.class));
                        activity.finish();
                        break;
                }
                break;
            //身份证未审核
            //身份证失败
            case "10":
            case "12":
                activity.mVp.setCurrentItem(1);
                break;
        }
    }

    private void notifyPayDone() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).notifyPayDone(((MyApplication) getActivity().getApplication()).getRequestFieldMap(),
                SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.PAY_TRADE_NO),
                "0").enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
            }
        });

    }


    @OnClick({R.id.pay_Cardeposit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pay_Cardeposit:
                MobclickAgent.onEvent(this.getActivity(), Constants.PAY_DEPOSIT);
                //缴纳保证金
                switch (payMethod) {
                    case 1:
                        getWXpayParams(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_CAR) + "");
                        break;
                    case 2:
                        getAlipayParams(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_CAR) + "");
                        break;
                }
                break;
        }
    }

    private void getWXpayParams(String chargeValue) {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).weChatDeposit(((MyApplication) getActivity().getApplication()).getRequestFieldMap(), chargeValue, "2", "1").enqueue(new Callback<WXPreBean>() {
            @Override
            public void onResponse(Call<WXPreBean> call, Response<WXPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 0);
                        WXPreBean.AttachmentBean.BeanBean orderInfo = response.body().getAttachment().getBean();
                        WXPayUtils wxPayUtils = new WXPayUtils(mContext);
                        wxPayUtils.wxPay(orderInfo);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WXPreBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getAlipayParams(String chargeValue) {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).aliPayDeposit(((MyApplication) getActivity().getApplication()).getRequestFieldMap(), chargeValue, "1", "1").enqueue(new Callback<AlipayPreBean>() {
            @Override
            public void onResponse(Call<AlipayPreBean> call, Response<AlipayPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 0);
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.PAY_TRADE_NO,
                                response.body().getAttachment().getOutTradeNo());
                        String orderInfo = response.body().getAttachment().getStr();
                        AlipayUtils alipayUtils = new AlipayUtils(getActivity());
                        alipayUtils.aliPay(orderInfo);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AlipayPreBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //viewpager的监听器打开位置为0的 mVp.setCurrentItem(0)不会触发监听器。
    private void deposit() {

    }

}
